package io.lckgroup.modules.lck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gexin.rp.sdk.base.IPushResult;
import io.lckgroup.modules.lck.dao.OrderMainDao;
import io.lckgroup.modules.lck.dao.ShopFoodDao;
import io.lckgroup.modules.lck.dao.ShopMerchantInfoDao;
import io.lckgroup.modules.lck.entity.OrderDetailEntity;
import io.lckgroup.modules.lck.entity.OrderMainEntity;
import io.lckgroup.modules.lck.entity.ShopFoodEntity;
import io.lckgroup.modules.lck.entity.ShopMerchantInfoEntity;
import io.lckgroup.modules.lck.service.OrderDetailService;
import io.lckgroup.modules.lck.service.WeixinCallbackService;
import io.lckgroup.modules.lck.utils.UniPushUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huangrui
 */
@Service
public class WeixinCallbackServiceImpl implements WeixinCallbackService {
    @Autowired
    private OrderMainDao orderMainDao;

    @Autowired
    private ShopMerchantInfoDao shopMerchantInfoDao;


    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShopFoodDao shopFoodDao;


    /**
     * 功能描述: <br>
     * 〈〉回调，修改订单状态
     *
     * @Param: []
     * @Return: void
     * @Author: 13980
     * @Date: 2020/3/11 18:25
     */
    @Override
    @CacheEvict(value = "weixinGetOrderList", allEntries = true)
    public String weixinChangeOrderState(Map<String, Object> map) {
        OrderMainEntity oldmainEntity = new OrderMainEntity();
        OrderMainEntity wrappmainEntity = new OrderMainEntity();
        oldmainEntity.setOrderId(map.get("outTradeNo").toString());
        wrappmainEntity.setIsPay(1);
        wrappmainEntity.setPayWay("微信");
        QueryWrapper<OrderMainEntity> wrapper = new QueryWrapper<>();
        wrapper.setEntity(oldmainEntity);
        orderMainDao.update(wrappmainEntity, wrapper);
        //通过商户号查询 client_id
        ShopMerchantInfoEntity shopMerchantInfoEntity = shopMerchantInfoDao.selectOne(new QueryWrapper<ShopMerchantInfoEntity>().eq("merchant_no", map.get("merchantNo").toString()));
        //商家名称 shopMerchantInfoEntity 商家信息表
        shopMerchantInfoEntity.getMerchantName();
        //OrderMainEntity
        OrderMainEntity oldMainEntity = orderMainDao.selectOne(new QueryWrapper<OrderMainEntity>().eq("order_id", map.get("outTradeNo").toString()));
        //食品详情 list
        List<OrderDetailEntity> listOrderDetails = orderDetailService.selectOrderDetail(oldMainEntity.getId());
        //查询  食品名字 list
        List<ShopFoodEntity> listFoodName = new ArrayList<>();
//        根据订单详情数组 查询菜品并且加入list
        for (OrderDetailEntity detail : listOrderDetails) {
            listFoodName.add(shopFoodDao.selectById(detail.getFoodId()));
        }
//        1.准备数据
        String CID = shopMerchantInfoEntity.getClientId();
//        2.订单信息mytest
        String mytest = "";
//        //取餐号 1小程序到店订单：桌号 2小程序到店订单：时间 3智能POS机到店订单：叫餐号
        int orderType = oldMainEntity.getOrderType();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (orderType == 1) {
            StringBuffer sb = new StringBuffer().append("\t").append(shopMerchantInfoEntity.getMerchantName()).append("新到订单信息\r\n")
                    .append("---------------------------------\r\n")
                    .append("订单号：").append(oldMainEntity.getOrderId()).append("\r\n")
                    .append("桌号：").append(oldMainEntity.getTableNum()).append("\r\n")
                    .append("用餐人数：").append(oldMainEntity.getPeopleNum()).append("\r\n")
                    .append("下单时间：").append(formatter.format(oldMainEntity.getGmtCreate())).append("\r\n")
                    .append("---------------------------------\r\n");
            for (int i = 0; i < listFoodName.size(); i++) {
                String foodSpecs = listOrderDetails.get(i).getFoodSpecs();
                if (StringUtils.isBlank(listOrderDetails.get(i).getFoodSpecs())) {
                    foodSpecs = "";
                }
                sb.append(listFoodName.get(i).getGoodsName()).append(":  ").append(listOrderDetails.get(i).getFoodNum() + "份 ")
//                         有价格的
                        .append(foodSpecs + " ").append("\r\n");
            }
            sb.append("---------------------------------\r\n").append("备注：" + oldMainEntity.getCustomerRemarks() + "\r\n")
                    .append("共计：" + oldMainEntity.getOrderPrice());
            mytest = sb.toString();
        }
        if (orderType == 2) {
            StringBuffer sb = new StringBuffer().append("\t").append(shopMerchantInfoEntity.getMerchantName()).append("新到订单信息\r\n")
                    .append("---------------------------------\r\n")
                    .append("订单号：").append(oldMainEntity.getOrderId()).append("\r\n")
                    .append("预留电话：").append(oldMainEntity.getCustomerTel()).append("\r\n")
                    .append("用餐人数：").append(oldMainEntity.getPeopleNum()).append("\r\n")
                    .append("预约时间：").append(formatter.format(oldMainEntity.getAppointmentTime())).append("\r\n")
                    .append("---------------------------------\r\n");
            for (int i = 0; i < listFoodName.size(); i++) {
                String foodSpecs = listOrderDetails.get(i).getFoodSpecs();
                if (StringUtils.isBlank(listOrderDetails.get(i).getFoodSpecs())) {
                    foodSpecs = "";
                }
                sb.append(listFoodName.get(i).getGoodsName()).append(":  ").append(listOrderDetails.get(i).getFoodNum() + "份 ")
//                         有价格的
                        .append(foodSpecs + " ").append("\r\n");
            }
            sb.append("---------------------------------\r\n").append("备注：" + oldMainEntity.getCustomerRemarks() + "\r\n")
                    .append("共计：" + oldMainEntity.getOrderPrice());
            mytest = sb.toString();
        }
        if (orderType == 3) {

        }
//        开始推送
        IPushResult iPushResult = UniPushUtils.pushOrderMsg(CID, mytest);
        if(iPushResult!=null){
            Map<String, Object> response = iPushResult.getResponse();
            if(response.get("result")=="ok"){
                return "ok";
            }
        }

        return "ok";
    }

    /**
     * 功能描述: <br>
     * 〈〉 判断当前订单是否支付过
     *
     * @Param: [orderId]
     * @Return: boolean   true未支付   false已支付
     * @Author: 13980
     * @Date: 2020/3/13 11:47
     */
    @Override
    public boolean weixinIsPay(String orderId) {
        OrderMainEntity orderMainEntity = new OrderMainEntity();
        orderMainEntity.setOrderId(orderId);
        QueryWrapper<OrderMainEntity> wrapper = new QueryWrapper<>();
        wrapper.setEntity(orderMainEntity);
        OrderMainEntity entity = orderMainDao.selectOne(wrapper);
        if (entity.getIsPay() == 0 || entity.getIsPay() == 2) {
            return true;
        }
        return false;
    }
}